// 1. 拿到 id 和 token, 验证是否存在
const contentBox = document.querySelector('.content')

//localStorage 那数据
const cartList = JSON.parse(window.localStorage.getItem('cart')) || []
// 验证是否真实, 如果有问题, 直接跳转回到 login 页面
const id = window.localStorage.getItem('id')

console.log(cartList);
loginTest()
async function loginTest() {
  if (!id) {
    // 把页面的标识信息存储起来
    window.localStorage.setItem('url', 'cart')
    // 跳转页面
    window.location.href = './login.html'
    return
  }


  // 2-2. 进行购物车列表的请求
  const res = await pAjax({
    url: './js/json/resultData.json',
    data: `id=${id}`,
    dataType: 'json',        
  })
  bindHtml(res)
}

function bindHtml(res){
  console.log(res);

  const cart = res.resultData.filter(item =>{item.id==id})
  console.log(id);
  console.log(cart);

  const selectNum = cart.filter(item =>item.is_select === true).length


  let str = `
  
        <div class="top">
        <input type="checkbox" ${selectNum === cart.length? 'checked':''}> 全选
      </div>
      <div class="center">
        <ul>
          `
          res.resultData.forEach(item =>{
            str +=`
            <li>
                <div class="select">
                  <input data-id="${item.id}" type="checkbox" class="item" ${ item.is_select ? 'checked' : ''}>
                </div>
                <div class="img">
                  <img src="${item.verticalPic}" alt="">
                </div>
                <div class="desc">${item.description}</div>
                <div class="price">${item.price}</div>
                <div class="number">
                  <button>-</button>
                  <input type="text" value="${item.cart_number}">
                  <button>+</button>
                </div>
                <div class="xiaoji">
                ${(item.price * item.cart_number).toFixed(2) }
                </div>
                <div class="delete">
                  <button>删除</button>
                </div>
            </li>
            `
          })
          str +=
          `  
        </ul>

      </div>
      <div class="bottom">
        <p class="number">
          购买数量 : <span>3</span>
        </p>
        <p class="btns">
          <button disabled>去结算</button>
          <button disabled>清空购物车</button>
          <button disabled>删除所有已选中</button>
        </p>
        <p class="totalPrice">
          总价 : <span>100.00</span>
        </p>
      </div>  
  `
  contentBox.innerHTML = str
}

//点击事件
//事件委托
contentBox.addEventListener('click', async e =>{
  e = e || window.event
  const target = e.target || e.srcElement
  if(target.className === 'item'){
    const goodsId = target.dataset.id
    const res = await $.ajax({
      url: './js/json/resultData.json',
      data:`id=${id}&goodsId=${goodsId}`,
      dataType:'json',
      method:'post'
    })
    loginTest()
    console.log(res);
  }
})
